import { asyncRoutes, constantRoutes } from '@/router'
// import comUtils from "@/utils/common"
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

// 原生路由表map与本地配置异步路由表对比 得到生成的远程路由表
export function getDiffOriginRoutes(routeConfig ,deepRoute){
  const { localRoutes , originRoutes  , deepKey } = routeConfig
  const diffRoutes = deepRoute || [];
  if( originRoutes && originRoutes.length ){
    originRoutes.forEach((originRouteItem) =>{
      const findLocalRoute = localRoutes.find(localRouteItem=>{
          return localRouteItem.path === originRouteItem.path 
          || localRouteItem.name === originRouteItem.name 
      })
      // 如果对比查找到本地对应层级的路由表
      if( findLocalRoute ){
        // 合并规则待定
        const copyDiffRoute = Object.assign({}, findLocalRoute , originRouteItem  ,{ children:[] })
        // 如果远程路由文件路径存在
        if( copyDiffRoute.url ){
          copyDiffRoute.component = (resolve) => require(["@/views"+ originRouteItem.url ], resolve)
        }
        diffRoutes.push( copyDiffRoute )
        // 继续迭代远程路由的子路由
        getDiffOriginRoutes({
          originRoutes: originRouteItem[deepKey] 
          ,localRoutes: findLocalRoute.children
          ,deepKey:"children"
        }, copyDiffRoute.children )
      }else{
        // 如果没有查找到对应路由表  看看是否有配置路由文件路径
        // 同时必须有  路由路径 或者 路由名称 具备创建一个路由的基本条件
        if( originRouteItem.url ){
          if( originRouteItem.path || originRouteItem.name ){
            //创建一个新路由
            const originRouteItem_created = Object.assign({},originRouteItem,{
              children:[],
              component: (resolve) => require(["@/views"+ originRouteItem.url ], resolve)
            })
            diffRoutes.push( originRouteItem_created )
            // 继续迭代远程路由的子路由
              getDiffOriginRoutes({
                originRoutes: originRouteItem[deepKey] 
                ,localRoutes: []
                ,deepKey:"children"
              }, originRouteItem_created.children )
          }else{
            throw Error("Please configure routing path or routing name")
          }
        }else{
         console.warn(`the origin route name ${ originRouteItem.name } is not find in localRoutes`)
        }
      }
    })
  }

  return diffRoutes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, routeConfig ) {
    return new Promise(resolve => {
      const { roles= ["admin"] , routes:originRoutes } = routeConfig

      let accessedRoutes 
      // 如果远程路由表存在的情况下
      if( originRoutes && originRoutes.length ){
        accessedRoutes =  getDiffOriginRoutes({
          originRoutes 
          ,localRoutes: asyncRoutes
          , roles // 暂无作用
          , deepKey:"children"
        })
      }else{
        // 纯角色筛选
        if (roles.includes('admin')) {
          accessedRoutes = asyncRoutes || []
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
      }

      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
